package leetcode.中等;

import org.junit.Test;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Set;

public class leetcode3_无重复字符的最长子串 {

    @Test
    public void test(){
//        System.out.println(3136321);
//        System.out.println(longestString("abcabcbb"));
//        System.out.println(longestString("bbbbb"));
//        System.out.println(longestString("pwwkew"));
        System.out.println(longestString("asjrgapa"));
//        System.out.println(longestString("dvdf"));
//        System.out.println(longestString("au"));
//        System.out.println(" ".length());
    }

    /**
     * 滑动窗口问题 双指针解决法
     * @param s
     * @return
     */
    public int lengthOfLongestSubstring(String s) {

        if (s.length()==1||s.length()==0){
            return s.length();
        }
        int left = 0;
        int right = 0;
        int length = 0;
        Set<Character> re = new HashSet<>();

        while(right<s.length()){
            if (!re.contains(s.charAt(right))){
                re.add(s.charAt(right));
                right++;
            }else {
                length= length>right-left?length:right-left;
                left++;
                right=left;
                re.clear();
            }
        }
        return Math.max(length,re.toArray().length);
    }

    /**i
     * 滑动窗口高效解决法
     * 左边每次循环减1，右边每次加1
     */
    public int lengthOfLongestSubstringWindows(String s) {
        int res = 0,right = 0;
        HashSet<Character> set = new HashSet<>();
        for (int i =0;i<s.length();i++){
            if(i!=0){
                set.remove(s.charAt(i-1));
            }
            while(right+1<s.length()&&!set.contains(s.charAt(right+1))){
                set.add(s.charAt(right+1));
                right++;
            }
            res = Math.max(res,right-i+1);
        }
        return res;
    }


    public int longestString(String s){
        // 哈希集合，记录每个字符是否出现过
        Set<Character> occ = new HashSet<Character>();
        int n = s.length();
        // 右指针，初始值为 -1，相当于我们在字符串的左边界的左侧，还没有开始移动
        int rk = -1, ans = 0;
        for (int i = 0; i < n; ++i) {
            if (i != 0) {
                // 左指针向右移动一格，移除一个字符
                occ.remove(s.charAt(i - 1));
            }
            while (rk + 1 < n && !occ.contains(s.charAt(rk + 1))) {
                // 不断地移动右指针
                occ.add(s.charAt(rk + 1));
                ++rk;
            }
            // 第 i 到 rk 个字符是一个极长的无重复字符子串
            ans = Math.max(ans, rk - i + 1);
        }
        return ans;

    }

}
